#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/shm.h>

#ifndef _SHMDATA_H_HEADER
#define _SHMDATA_H_HEADER
 
#define TEXT_SZ 3
struct shared_use_st{
    int written_s;//作为一个标志，非0：表示可读，0表示可写
    int written_r;
    int text[TEXT_SZ];//记录写入和读取的文本
};
#endif

int main()
{
    int count=0;

    void *shm = NULL; //分配的共享内存的原始首地址
    struct shared_use_st *shared; //指向shm
    int shmid;   //共享内存标识符
    //创建共享内存

    //shmid = shmget((key_t)1234, sizeof(struct shared_use_st),IPC_CREAT);
    shmid = shmget(1000, sizeof(struct shared_use_st), 0666 | IPC_CREAT);

    if(shmid == -1){
        fprintf(stderr, "shmget failed\n");
        exit(EXIT_FAILURE);
    }
    //将共享内存连接到当前进程的地址空间
    shm = shmat(shmid, 0, 0);

    if(shm == (void*)-1){
        fprintf(stderr, "shmat failed\n");
        exit(EXIT_FAILURE);
    }
    printf("\nMemory attached");
    //设置共享内存
    shared = (struct shared_use_st*)shm;
    shared->written_r=0;
    while(count<=10){ //读取共享内存中的数据
        while(shared->written_s==0){ //有其他进程在写数据，不能读取数据
            sleep(1);
            printf("waiting......");
        }
        //没有进程向共享内存定数据有数据可读取
        printf("get numbers:a--%d  b--%d\n",shared->text[0],shared->text[1]);
        shared->text[2]=shared->text[0]+shared->text[1];
        printf("result:%d\n",shared->text[2]);
        shared->written_r=1;
        shared->written_s=0;
    }
    //把共享内存从当前进程中分离
    if(shmdt(shm) == -1){
        fprintf(stderr, "shmdt failed\n");
        exit(EXIT_FAILURE);
    }
    //删除共享内存
    if(shmctl(shmid, IPC_RMID, 0) == -1){
        fprintf(stderr, "shmctl(IPC_RMID) failed\n");
        exit(EXIT_FAILURE);
    }
    exit(EXIT_SUCCESS);
}